
package shthon2011s.eroid;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.Toast;

public class SettingsActivity extends Activity {

    private SettingsActivity self = this;

    private static final String PREF_FILENAME = "pref";

    public static final String PREF_KEY_NAME = "name";

    private EditText mUserName;

    public static SharedPreferences getSharedPreferences(Context ctxt) {
        final SharedPreferences pref = ctxt.getSharedPreferences(PREF_FILENAME, 0);
        return pref;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.settings);

        mUserName = (EditText) findViewById(R.id.user_name);

        findViewById(R.id.ok).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (v.getId() != R.id.ok) {
                    return;
                }

                final String userName = mUserName.getText().toString();
                if (userName.isEmpty()) {
                    Toast.makeText(self, "名前を入力してください", Toast.LENGTH_SHORT).show();
                    return;
                }

                final SharedPreferences preferences = SettingsActivity.getSharedPreferences(self);
                final Editor prefEditor = preferences.edit();

                prefEditor.putString(PREF_KEY_NAME, userName);

                final boolean committed = prefEditor.commit();
                if (committed) {
                    setResult(Activity.RESULT_OK);
                } else {
                    setResult(Activity.RESULT_CANCELED);
                    Toast.makeText(self, "登録に失敗しました", Toast.LENGTH_LONG).show();
                }
                finish();
            }
        });
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        setResult(Activity.RESULT_CANCELED);
        finish();
    }
}
